package com.powerunion.datacollection.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.UsersRolesDao;
import com.powerunion.datacollection.model.UsersRoles;
import com.powerunion.datacollection.model.jsonObject.JSONDataBean;
import com.powerunion.util.log.LogHelper;


public class UsersRolesManager {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			UsersRolesManager.class);
	
	private UsersRolesDao usersRolesDao = null;
	
	public UsersRolesManager() {
		super();
		try {
			this.usersRolesDao = (UsersRolesDao)DaoFactory.getInstance().getDao(UsersRolesDao.class);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public boolean save (List users,String roleId) throws Exception {
		//参数为空
		if( StringUtils.isEmpty(roleId) ) {
			String[] args = {"roleId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter roleId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}	
		//保存的时候先删除该角色原先的所有记录再重新保存 
		this.usersRolesDao.delete(roleId);
		
		return this.usersRolesDao.save(users, roleId);
	}
	
	public String getUsersByRole(String roleId) throws Exception {
//		//参数为空
//		if(StringUtils.isEmpty(roleId) ) {
//			String[] args = { "roleId" };
//			// 打印错误日志
//			StringBuffer msglog = new StringBuffer(
//					"empty invoke parameter roleId NULL ");
//			logger.error(msglog.toString());
//			throw new SystemException("error.common.parameter.empty", args);
//		}	
		
		List list = this.usersRolesDao.getUsersByRole(roleId);
		JSONArray jSONArray = JSONArray.fromObject(list);
		logger.debug("角色roleId:"+roleId+"下对应的用户:"+jSONArray);
		String result = "{results:"+jSONArray+"}";
		return result;
	}
	
	public boolean delete(String roleId) throws DaoException {
		//参数为空
		if(StringUtils.isEmpty(roleId) ) {
			String[] args = { "roleId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter roleId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}	
		return this.usersRolesDao.delete(roleId);
	}
}
